<?php

class Application_Model_CircuitDAO
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if(is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if(!$dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
	public function getDbTable()
	{
		if(null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Circuit');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Circuit $circuit)
	{
		$data = array(
			'CIRNUM' => $circuit->getCirNum(),
			'PAYNUM' => $circuit->getPays()->getPayNum(),
			'CIRNOM' => $circuit->getCirNom(),
			'CIRLONGUEUR' => $circuit->getCirLongueur(),
			'CIRNBSPECTATEURS' => $circuit->getCirNbSpectateurs(),
			'CIRADRESSEIMAGE' => $circuit->getCirAdresseImage(),
			'CIRTEXT' => $circuit->getCirText()
		);
 
		if (null === ($cirNum = $circuit->getCirNum()))
		{
			unset($data['CIRNUM']);
			//$this->getDbTable()->insert($data);
        }
        else
        {
			$this->getDbTable()->update($data, array('CIRNUM = ?' => $cirNum));
		}
		return true;
	}
	
	public function delete($id)
	{
		$grandprixDAO = new Application_Model_GrandprixDAO();
		$grandprixDbTable = new Application_Model_DbTable_Grandprix();
		$resultSet = $grandprixDbTable->fetchAll($grandprixDbTable->select()->from('grandprix',array('GPNUM'))->where('CIRNUM = '.$id));
		$entries = array();
		foreach($resultSet as $row)
		{
			$grandprixDAO->delete($row->GPNUM);
		}
		$this->getDbTable()->delete(array('CIRNUM = ?' => $id));
	}
	
	public function find($cirNum)
	{
		$circuit = new Application_Model_Circuit();
		$paysDAO = new Application_Model_PaysDAO();
		$result = $this->getDbTable()->find($cirNum);
		if(0 == count($result))
		{
			return null;
		}
		$row = $result->current();
		$circuit->setCirNum($row->CIRNUM)
				->setCirNom($row->CIRNOM)
				->setCirLongueur($row->CIRLONGUEUR)
				->setCirNbSpectateurs($row->CIRNBSPECTATEURS)
				->setCirAdresseImage($row->CIRADRESSEIMAGE)
				->setCirText($row->CIRTEXT);
			   
		//On recupere le pays
		$pays = $paysDAO->find($row->PAYNUM);
		$circuit->setPays($pays);
		
		return $circuit;
	}
	
	public function findAll()
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('circuit',array('CIRNUM'))->order('CIRNOM ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->CIRNUM);
		}
		return $entries;
	}
}